<?php
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Input as Input;
use App\Services\UserService;
use App\Services\OAuthService;

class OAuthController extends BaseController
{

	protected $OAuth;
	protected $auth;
	protected $userService;
	protected $layout = 'layouts.master';

	public function __construct(OAuthService $OAuthService, UserService $userService, \Illuminate\Support\Facades\Auth $auth)
	{
		$this->userService = $userService;
		$this->auth = $auth;
		$this->OAuth = $OAuthService;

	}

	public function getCode()
	{
		$code = Input::get('code', null);
		if (!$code) {
			return Response::view('errors.403_json', ['data' => ['error' => 'Invalid Session', 'code' => '401_2']])->header('Content-Type', 'application/json')->setStatusCode(403); // Token expired/invalid (Esri)
		}

		return $this->makeView('wx_login_json', $code);
	}

	public function getUser()
	{
		$code = Input::get('code', null);
		$state = Input::get('state', null);
		if (!$code || !$state) {
			return Response::view('errors.403_json', ['data' => ['error' => 'Invalid Session', 'code' => '401_2']])->header('Content-Type', 'application/json')->setStatusCode(403); // Token expired/invalid (Esri)
		}

		$user_info = $this->OAuth->get_user_info($state, $code);
		if (!$user_info) {
			return Response::view('errors.403_json', ['data' => ['error' => 'Invalid Session', 'code' => '401_2']])->header('Content-Type', 'application/json')->setStatusCode(403); // Token expired/invalid (Esri)
		}

		if($state == 'wx'){
			$union_id = $user_info['unionid'];
		}elseif($state == 'qq'){
			$union_id = Session::get('qq_open_id', '');
		}
		return $this->makeView('home.login_json', ['union_id'=>$union_id, 'platform'=>$state]);

	}

	public function updatePhone()
	{
		$post = Input::all();
		$rules = [
			'user_id' => 'required',
			'phone'   => 'required',
		];
		$messages = [
			'user_id.required' => '用户ID必须有',
			'user_id.required' => '用户ID必须有',
		];
		$validator = Validator::make($post, $rules, $messages);
		if ($validator->fails()) {
			// the given data did not pass validation
			return $this->makeView('errors.400', $validator->errors(), 400);
		}

		$user_id = Input::get('user_id', null);
		$phone = Input::get('phone', null);
		$this->updatePhone($user_id);
	}

}
